package com.leo.controller;

import com.leo.EmailFxApp;
import com.leo.bean.EmailInfo;
import com.leo.bean.MessageInfo;
import com.leo.common.ApplicationContentUtil;
import com.leo.common.MailApiUtil;
import com.leo.common.MailViewUtils;
import com.leo.common.TextFieldTreeCellImpl;
import com.leo.db.DaoMapperProxy;
import com.leo.mapper.UserMapper;
import com.leo.view.AddMailVIew;
import com.leo.view.SendEmailView;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.scene.control.SplitPane;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.Region;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

import static com.leo.EmailFxApp.executorService;

/**
 * @author wangss
 * @date 2023/02/18 21:59
 * @description 邮箱主页面
 **/
@Slf4j
public class MainController {

    @FXML
    private SplitPane centerSplitPane;

    @FXML
    private SplitPane contentSplitPane;

    /**
     * 邮件主面板
     */
    @FXML
    private BorderPane emailBorder;

    /**
     * 邮件内容信息
     */
    @FXML
    private StackPane emailContentPane;

    /**
     * 邮件列表信息
     */
    @FXML
    private VBox emailContentVbox;

    /**
     * 最左侧邮箱用户信息
     */
    @FXML
    private VBox emailVbox;

    private TreeView<String> treeView;
    private TreeItem root;

    @FXML
    void initialize() {
        // 加载样式
        emailBorder.getStylesheets().add(EmailFxApp.class.getResource("css/email.css").toExternalForm());
        // 初始化邮箱列表
        initMailUserList();
        // 查看是否配置邮箱，如果没有配置则弹出配置框
        int userId = (Integer) ApplicationContentUtil.getContentMapValue("userId");
        UserMapper userMapper = DaoMapperProxy.getProxyInstance(UserMapper.class);
        List<EmailInfo> emailInfos = userMapper.selectByUserId(userId);
        if (null == emailInfos || emailInfos.isEmpty()) {
            // 用户不存在邮箱信息，则进行新增
            initNoMailUserList(userId);
        } else {
            // 用户存在邮箱信息，则进行初始化
            MailViewUtils.addMailUserList(emailInfos, root, emailContentPane);
            // 获取第一个邮箱
            EmailInfo emailInfo = emailInfos.get(0);
            // 获取邮箱下所有邮件，并根据状态放到不同的邮件列表中
            List<MessageInfo> messageInfos = userMapper.selectMessageInfoByMailId(emailInfo.getId());
            messageInfos.stream().forEach(messageInfo -> {
                messageInfo.setEmail_info_id(emailInfo.getId());
                int status = messageInfo.getStatus();
                if (status == 0 || status == 2) {
                    ApplicationContentUtil.receiveList.add(messageInfo);
                } else if (status == 4) {
                    ApplicationContentUtil.draftList.add(messageInfo);
                } else if (status == 1) {
                    ApplicationContentUtil.garbageList.add(messageInfo);
                } else if (status == 3) {
                    ApplicationContentUtil.sendList.add(messageInfo);
                }
            });
        }

        initSplitPane();
    }

    /**
     * 初始化邮箱用户列表
     */
    private void initMailUserList() {
        root = new TreeItem("root");
        treeView = new TreeView(root);
        treeView.setPrefHeight(emailVbox.getPrefHeight());
        emailVbox.getChildren().add(treeView);
        treeView.setShowRoot(false);
        treeView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, newValue) -> {
            // 根据选择的treeitem展示不同的邮件列表
            MailViewUtils.changeTreeViewVisible(newValue.getValue(), emailContentVbox);
        });

        // 设置树形结构可编辑
        treeView.setEditable(true);
        // 将treeView对象的选项节点元素设置成自定义的TreeCell实现
        treeView.setCellFactory(param -> new TextFieldTreeCellImpl());
    }

    /**
     * 用户不存在邮箱信息时界面初始化
     *
     * @param userId
     */
    private void initNoMailUserList(int userId) {
        StackPane addEmailBtn = new StackPane();
        Region region = new Region();
        addEmailBtn.getStyleClass().add("addEmailBtn");
        addEmailBtn.getChildren().add(region);
        emailContentPane.getChildren().add(addEmailBtn);
        addEmailBtn.setOnMouseClicked(event -> {
            new AddMailVIew(userId, emailContentPane, addEmailBtn, root);
        });
    }

    /**
     * 收信
     **/
    public void receiveMailAction(ActionEvent actionEvent) {
        String email = (String) ApplicationContentUtil.getContentMapValue("currentEmail");
        EmailInfo mailBean = (EmailInfo) ApplicationContentUtil.getContentMapValue(email);
        Task<String> task = new Task<>() {
            @Override
            protected String call() throws Exception {
                MailApiUtil.reveiveMail(mailBean);
                return null;
            }
        };
        executorService.submit(task);
    }

    /**
     * 写信
     **/
    public void writeMailAction(ActionEvent actionEvent) {
        String email = (String) ApplicationContentUtil.getContentMapValue("currentEmail");
        EmailInfo mailBean = (EmailInfo) ApplicationContentUtil.getContentMapValue(email);
        // 打开写信界面
        new SendEmailView(mailBean, new MessageInfo());
    }

    /**
     * @description: 初始化分割线
     * @author: wangss
     **/
    public void initSplitPane() {
        for (SplitPane.Divider divider : centerSplitPane.getDividers()) {
            divider.positionProperty().addListener((observable, oldValue, newValue) -> divider.setPosition(0.15));
        }

        for (SplitPane.Divider divider : contentSplitPane.getDividers()) {
            divider.positionProperty().addListener((observable, oldValue, newValue) -> {
                emailContentVbox.setPrefWidth(contentSplitPane.getPrefWidth() * newValue.doubleValue());
                if (0.26 >= newValue.doubleValue()) {
                    divider.setPosition(0.26);
                } else if (0.3 <= newValue.doubleValue()) {
                    divider.setPosition(0.3);
                }
            });
        }
    }
}
